<?php
/**
 * TaskController
 *-------------------------
 *
 * Deal with menu display, selected status. Top menu - sub menu 
 *
 * PHP versions 5
 *
 * LICENSE: This source file is from Smarter Ver4.0, which is a comprehensive shopping engine
 * that helps consumers to make smarter buying decisions online. We empower consumers to compare
 * the attributes of over one million products in the computer and consumer electronics categories
 * and to read user product reviews in order to make informed purchase decisions. Consumers can then
 * research the latest promotional and pricing information on products listed at a wide selection of
 * online merchants, and read user reviews on those merchants.
 * The copyrights is reserved by http://www.mezimedia.com.
 * Copyright (c) 2005, Mezimedia. All rights reserved.
 *
 * @author     james.huang <james_huang@mezimedia.com>
 * @copyright  (C) 2004-2008 Mezimedia.com
 * @license    http://www.mezimedia.com  PHP License 5.2
 * @version    CVS: $Id: UserController.php
 * @link       http://pms.mezimedia.com/
 * @deprecated File deprecated in Release 1.0
 */
 
require_once 'Zend/Session/Namespace.php';
require_once 'Zend/Json.php'; // for ajax piedata

require_once('app/model/Task.php');
require_once('app/model/TaskUpdate.php');
require_once('app/model/User.php');
require_once('app/model/Message.php');
require_once('app/model/Score.php');

require_once('app/lib/Pager.php');
require_once('app/lib/Tree.php');

class TaskController extends Zend_Controller_Action
{
	public $task_tree = null;
	public $task_content = '';
	public $bg_color = array(
		'#fff', '#eee', '#ddd', '#ccc'
	);
	public $page_size = 20; // each page item number
	public $pm_roles = array('admin', 'rt', 'pm');
	public $tl_roles = array('tl');
	
	function preDispatch()
	{		
		// For user role and task ACL control
		$this->view->user = Zend_Auth::getInstance()->getIdentity();
		$this->view->acl = $this->acl = Zend_Registry::get('acl');
		
		// Page menulist 
		$this->view->controller = $this->_request->getControllerName();
		$this->view->action = $this->_request->getActionName();
		$subMenu = array (
			'Active' => array (
				'key' => 'index',
				'url' => '/task/',
				'selected' => false,
				'title' => 'Active Task list',
			),
			'Completed' => array (
				'key' => 'finish',
				'url' => '/task/finish',
				'selected' => false,
				'title' => 'Completed Tasks List'
			),
			'Configure' => array (
				'key' => 'config',
				'url' => '/task/config',
				'selected' => false,
				'title' => 'Task Configure',
			)
		);
		$menu = new Menu();
		$menuTree = $menu->renderMenu($this->_request->getControllerName(), $this->_request->getActionName(), $subMenu);
		$this->view->menuTree = $menuTree;

		// Page namespace
		$this->tns = new Zend_Session_Namespace('TT_Task');
		$this->tns->now_page = $this->_getParam('p') ? $this->_getParam('p') : 1;

		// Page useful url
		$this->task_id = $this->_getParam('id') ? $this->_getParam('id') : 0;
		
		$this->view->base_url		= '/task/';
		$this->view->this_url		= $_SERVER['REQUEST_URI'];
//		$this->view->referer_url	= $_SERVER['HTTP_REFERER'];
		$this->view->filter_url		= $this->view->base_url.'filter';
		$this->view->sorter_url		= $this->view->base_url.'sorter';
		$this->view->search_url		= $this->view->base_url.'search';
		$this->view->finish_url		= $this->view->base_url.'finish';
		$this->view->config_url		= $this->view->base_url.'config';
		$this->view->upload_url		= $this->view->base_url.'upload/id/'.$this->_getParam('id');
		$this->view->create_url		= ($this->tns->now_page > 1) ? $this->view->base_url.'new/p/'.$this->tns->now_page : $this->view->base_url.'new';
		$this->view->update_url		= ($this->tns->now_page > 1) ? $this->view->base_url.'edit/p/'.$this->tns->now_page : $this->view->base_url.'edit';
		$this->view->page_url		= ($this->tns->now_page > 1) ? $this->view->base_url.'index/p/'.$this->tns->now_page : $this->view->base_url.'index';
		$this->view->cancel_url		= $this->view->page_url.'/id/'.$this->task_id;
		$this->view->mess_url		= $this->view->base_url.'message';
		$this->view->mark_url		= $this->view->base_url.'mark';
		$this->view->pie_url		= $this->view->base_url.'piedata';
		$this->view->img_url		= $this->view->base_url.'process';
		
		// Page module var
		$this->oTask = new Task();
		
		// Task list level color style
		$level = $this->oTask->getEntities('level');
		array_shift($level); // remove '-- Selected --' item
		$this->bg_color = $level;
	}
	
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // action controller method

	public function configAction()
	{
		if ($this->_getParam('clean')) {
			$config = Zend_Registry::get('config');
			if (isset($config->cache->backend->cache_dir)) {
				$cache_path = realpath(__ROOT_PATH.$config->cache->backend->cache_dir);
				$command = "rm -rf {$cache_path}/*";
				@shell_exec($command);
				echo 'success';
			} else {
				echo 'failure';
			}
			exit;
		}
		
		if ($this->_getParam('save')) {
			$data = Utils::db_mk_row_data($this->oTask->_config->getConfigCols(), $this->_getAllParams());
//			Utils::dumper($data);
			try {
				$this->oTask->_config->updateConfig($data);
			}  catch (Exception $e) {
				$this->view->errors = array($e->getMessage());
			}
		}
		
		$configs = array();
		$configure = $this->oTask->_config->getAllConfigure();
		foreach ($configure as $config) {
			if ($config['name'] == 'level') {
				$this->view->level = explode(',', $config['value']);
			} else {
				array_push($configs, $config);
			}
		}
		
		$this->view->config = $configs;
	}

    /*
     * Task list for all
     */
	public function indexAction()
	{
		$this->taskFilter();
		$this->taskSorter();
		$this->initTaskTree();
		$ajaxView = $this->ajaxCallTaskTree();
		
		$this->plantTaskTree(); // plant a task tree
		$this->view->entites = $this->oTask->getEntities();
		$this->view->bg_color = $this->bg_color;
		
		return ($ajaxView) ? $this->render($ajaxView) : null;
	}

    /*
     * Task list user tasks which are not completed
     */
    public function finishAction()
    {
		$this->taskFilter(true);
		$this->initTaskTree(true);
		$ajaxView = $this->ajaxCallTaskTree(true);
		
		$this->plantTaskTree(true); // plant a task tree
		$this->view->entites = $this->oTask->getEntities();
		Zend_Loader :: loadClass('Team');
		$team = new Team();
		$teams = $team->findTeam('1');
		$teamlist = array();
		foreach($teams as $team) {
			$teamlist[$team['id']] = $team['name'];
		}
		$this->view->teams = $teamlist;
		$this->view->bg_color = $this->bg_color;
		
		return ($ajaxView) ? $this->render($ajaxView) : null;
    }
    
    public function sequenceAction() {
    	$sTaskId = $this->_getParam('sti');
    	$tTaskId = $this->_getParam('tti');
    	$this->oTask->setSequence($sTaskId, $tTaskId);
    	exit();
    }

	public function detailAction()
	{
		$task_id = $this->_getParam('id') ? $this->_getParam('id') : 0;
		$tasks = $this->oTask->find($task_id)->toArray();
		if (sizeof($tasks)) {
			$task = $tasks[0];
			$task['property']	= $this->oTask->getEntityValue('property', $task['property_id']);
			$task['requester']	= $this->oTask->getEntityValue('requester', $task['request_id']);
			$task['developer']	= $this->oTask->getEntityValue('engineer', $task['developer_id']);
			$task['manager']	= $this->oTask->getEntityValue('manager', $task['manager_id']);
			$task['prior']		= $this->oTask->getEntityValue('prior', $task['task_prior']);
			$task['type']		= $this->oTask->getEntityValue('status', $task['task_type']);
			$task['status']		= $this->oTask->getEntityValue('status', $task['task_status']);
			$task['process']	= $this->view->img_url.'?proc='.$task['progress'];
			$task['progress']	= $task['progress'].' %';
			$oTaskUpdate = new TaskUpdate();
			$task['task_updates'] = $oTaskUpdate->find('task_id = '.$task_id);
			$this->view->task	= $task;
		}
		$this->view->full_page	= true;
	}

	public function newAction()
	{
		// Add By James 08/05/22 ; for get right super tasks
		$this->taskFilter();
		// Add End
		
		$this->getChildrenWeight($this->task_id);
		
		if ($this->_getParam('save')) {
			// validation for title
			if (!$this->_getParam('title')) {
				$this->view->errors = array('Task title can not be empty!');
				$this->view->sup_id = $this->task_id;
				return ;
			}
			// fill task_prior column
			$data = Utils::db_mk_row_data($this->oTask->getCols(), $this->_getAllParams());
			$referId = isset($data['prior_reference']) ? $data['prior_reference'] : -1;
			$task_prior = $this->oTask->getTaskPrior($referId);
			if ($task_prior) $data['task_prior'] = $task_prior;
			$data['sequence'] = $this->oTask->markSequence();
			///Utils::dumper($data);exit;
			$insert_id = 0;
			try {
				$insert_id = $this->oTask->insert($data);
			}  catch (Exception $e) {
				$this->view->errors = array($e->getMessage());
			}
			// update sub task
			$tasks_weight = $this->getTaskWeight();
			if (sizeof($tasks_weight) > 0) {
				$this->oTask->updateWeight($tasks_weight);
			}
			// update parent schedule
			$this->updateTaskSchedule();
			
			// Add by James on 2008/05/15 for display added task after split
			if ($this->task_id && $insert_id) {
				$this->tns->selected_tasks = array_merge($this->tns->selected_tasks, array($this->task_id));
				$this->tns->display_tasks = array_merge($this->tns->display_tasks, array($insert_id));
			}
			// Add End
			
			$this->_redirect($this->view->cancel_url);
		}
		
		$this->view->entites = $this->oTask->getEntities();
		$this->view->sup_id = $this->task_id;
		
		// For sub task to inherit from
		$sup_tasks = $this->oTask->find($this->task_id)->toArray();
		if (sizeof($sup_tasks) > 0) {
			$this->view->sup_task = $sup_tasks[0];
//			Utils::dumper($sup_tasks[0]);
		}
	}
	
	public function editAction()
	{
		// Add By James 08/05/22 ; for get right super tasks
		$this->taskFilter();
		// Add End
		
		$this->getChildrenWeight($this->task_id);
		
		if ($this->_getParam('save')) {
			// validation for title
			if ($this->acl->isAllowed(null, 'modify:title') && !$this->_getParam('title')) {
				$this->view->errors = array('Task title can not be empty!');
				$this->view->sup_id = $this->task_id;
				return ;
			}
			// fill task_prior column
			$data = Utils::db_mk_row_data($this->oTask->getCols(), $this->_getAllParams());
			$referId = isset($data['prior_reference']) ? $data['prior_reference'] : -1;
			$task_prior = $this->oTask->getTaskPrior($referId);
			if ($task_prior) $data['task_prior'] = $task_prior;
			// append new task update to old
			if (!empty($data['task_update'])) {		
				$oTaskUpdate = new TaskUpdate();		
				$oTaskUpdate->insert($data, $this->_getParam('id'));
			}
			try {
				$this->oTask->update($data, $this->task_id);
			}  catch (Exception $e) {
				$this->view->errors = array($e->getMessage());
			}
			// update sub task
			$tasks_weight = $this->getTaskWeight();
			if (sizeof($tasks_weight) > 0) {
				$this->oTask->updateWeight($tasks_weight);
			}
			// update parent schedule
			$this->updateTaskSchedule();
			
			$this->_redirect($this->view->cancel_url);
		}
		
		$task_items = $this->oTask->find($this->task_id)->toArray();
		$oTaskUpdate = new TaskUpdate();
		$task_items[0]['task_updates'] = $oTaskUpdate->find('task_id = '.$this->task_id);
		$this->view->entites = $this->oTask->getEntities();
		$this->view->task = $task_items[0];
		// store old task updates for further update
		$this->tns->task_update_old = isset($task_items[0]['task_update']) ? $task_items[0]['task_update'] : "";
	}
	
	public function messageAction()
	{
		$oMessage = new Message();
		$data = Utils::db_mk_row_data($oMessage->getCols(), $this->_getAllParams());
		if (isset($data['userid']) && isset($data['taskid']) && isset($data['toid']) && isset($data['content'])) { 
			try {
				$data['adddate'] = date('Y-m-d H:i:s');
				$oMessage->insert($data);
			}  catch (Exception $e) {
				$this->view->errors = array($e->getMessage());
			}
			echo 'success';
		} else {
			echo 'failure';
		}
		exit;
	}
	
	public function markAction()
	{
		$oScore = new Score();
		$data = Utils::db_mk_row_data($oScore->getCols(), $this->_getAllParams());
		$fn = $this->_getParam('fn');
		if ($fn == 'get') {
			try {
				$tScore = $oScore->fetchRow('task_id='.$data['task_id'].' and team_id='.$data['team_id']);
				if($tScore) {
					$data = $tScore->toArray();
					echo Zend_Json::encode($data);
				} else {
					echo '{"efficiency":"0","response":"0","quality":"0","responsibility":"0","aggressive":"0","teamwork":"0"}';
				}
			} catch(Exception $e) {
				echo 'failure';
			}
			exit;
		} 
		if (isset($data['task_id'])) { 
			try {
				$tScore = $oScore->fetchRow('task_id = '.$data['task_id'].' and team_id='.$data['team_id']);
				$user = Zend_Auth::getInstance()->getIdentity();
				$data['user_id'] = $user['userId'];
				$data['update_time'] = date('Y-m-d H:i:s');
				if ($tScore) {
					$oScore->update($data, $tScore->__get('id'));
				} else {
					$oScore->insert($data);
				}
			}  catch (Exception $e) {
				$this->view->errors = array($e->getMessage());
			}
			echo 'success';
		} else {
			echo 'failure';
		}
		exit;
	}
	
	public function filterAction()
	{
//		Utils::dumper($this->_getAllParams());
		$k = $this->_getParam('k');
		$v = $this->_getParam('v');
		if ($this->_getParam('finished')) {
			if (strlen($k)> 0) {
				$this->tns->filter_finished[$k] = $v;
			}
		} else {
			if (strlen($k)> 0) {
				$this->tns->filter[$k] = $v;
			}
		}
		echo 'success';
		exit;
	}

	public function sorterAction()
	{
//		Utils::dumper($this->_getAllParams());
		$k = $this->_getParam('k');
		$v = $this->_getParam('v');
		if ($this->_getParam('finished')) {
			// Add code for complete task here ..
			
		} else {
			if (strlen($k)> 0) {
				$this->tns->sorter[$k] = $v;
			}
		}
		echo 'success';
		exit;
	}

	public function uploadAction ()
    {
		$task_id = $this->_getParam('id') ? $this->_getParam('id') : 0;
		
		// deal with the attachment upload
		if ($this->_getParam('has_attachment')) {
	        if ($this->uploadAttachment('attachment_file', $task_id)) {
	        	$this->oTask->update(array('attachment' => 1), $task_id);
	        }
		}
		
		// get attachment list
		$filelist = array();
		$filePath = __ROOT_PATH.'/data/tasks/'.$task_id;
		$httpPath = __ROOT_HOST.'/data/tasks/'.$task_id;
		if (file_exists($filePath)) {
			if ($handle = opendir($filePath)) {
				while ($file = readdir($handle)) {
					if ($file != "." && $file != ".." && $file != "Thumbs.db") {
						$path = $httpPath.'/'.$file;
						$icon = $this->getAttachmentIcon($file);
						array_push($filelist, array(
							'name'	=> $file,
							'icon'	=> $icon,
							'path'	=> $path,
						));
					}
				}
			}
			closedir($handle);
		}
		
		$this->view->filelist = $filelist;
    }

	public function searchAction() 
    {
        $this->_redirect('/'); 
    }
    
    // using amChart
	public function piedataAction()
	{
		if ($this->_getParam('ajax')) {
			$data = $this->_getParam('data');
			if ($data) {
				$ajax_tasks = Zend_Json::decode($data);
				if (is_array($ajax_tasks) && isset($this->tns->pietask)) {
					$now_tasks = $this->tns->pietask;
					$loop = 0;
					foreach ($ajax_tasks as $k => $v) {
						if (!isset($now_tasks[$loop])) {
							$now_tasks[$loop]['title'] = 'Current Task';
						}
						$now_tasks[$loop]['weight'] = $v;
						$loop++;
					}
					$this->pieData($now_tasks);
					echo 'success';
					exit;
				}
			}
			echo 'failure';
			exit;
		} else {
			echo $this->tns->piedata;
			exit;
		}
	}
	
	public function piesettingAction(){}
	
	public function processAction()
	{
		try{
			Header("Content-type: image/png");
			$proc 	= $this->_getParam('proc') ? intval($this->_getParam('proc')) : 0;
			$im 	= ImageCreate (50, 5);
			$bg		= imagecolorallocate($im, 255, 255, 0);
			$bgc	= imagecolorallocate($im, 255, 192, 0);
			$width	= intval($proc / 2);
			imagefilledrectangle($im, 0, 0, $width, 5, $bgc);
			imagepng($im);
			imagedestroy($im);
			exit;	
		}		
		catch(Exception $e)
		{
			var_dump($e);
		}
	}
    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // index action support method

	public function taskFilter ($finished = false) {
		if ($finished) {
			if (!isset($this->tns->filter_finished)) {
				$this->tns->filter_finished = array(
					'title'			=> '',
					'task_status'	=> 0,
					'task_prior'	=> 0,
					'request_id'	=> 0,
					'manager_id'	=> 0,
					'developer_id'	=> 0,
					'property_id'	=> 0,
				);
			}
			// Add By James for 'My Tasks'
			if ($this->_getParam('uid')) {
				$this->tns->filter_finished['developer_id'] = $this->_getParam('uid');
			}
			// Add End
			$this->oTask->setFilter($this->tns->filter_finished);
			$this->view->filter = $this->tns->filter_finished;
		} else {
			if (!isset($this->tns->filter)) {
				$this->tns->filter = array(
					'title'			=> '',
					'task_status'	=> 0,
					'task_prior'	=> 0,
					'request_id'	=> 0,
					'manager_id'	=> 0,
					'developer_id'	=> 0,
					'property_id'	=> 0,
				);
			}
			$this->oTask->setFilter($this->tns->filter);
			$this->view->filter = $this->tns->filter;
		}
	}

	public function taskSorter ($finished = false) {
		if ($finished) {
			// Add code for complete task here ..
			
		} else {
			if (!isset($this->tns->sorter)) {
				$this->tns->sorter = array(
					'sequence' => 'asc',
					'date_end' => 'asc',
				);
			}
			$this->oTask->setSorter($this->tns->sorter);
			$this->view->sorter = $this->tns->sorter;
		}
	}

	public function initTaskTree ($finished = false) {
		// get task tree by page id
		$pat = array(
			'Mode'		=> 2, 
			'Paging'	=> ($finished) ? '/task/finish/p/{page}' : '/task/index/p/{page}', 
			'Prev'		=> '<', 
			'Next'		=> '>'
		);
		$obj = new Pager($this->page_size, $this->tns->now_page, $this->oTask->getTotal($finished), $pat);
		$pager = $obj->toArray();
		$sup_ids = $this->oTask->getSuperTaskIds($pager['itemNum'], $pager['frNum'], $finished);
    	$this->oTask->getRawTaskList($sup_ids);
    	// build tree data structure
    	$sub_task_ids = array();
    	$sup_task_ids = array();
		$this->task_tree = new Tree();
		foreach ($this->oTask->_raw_task_list as $task) {
			$this->task_tree->setNode($task['id'], $task['sup_task_id'], $task);
			array_push($sup_task_ids, $task['sup_task_id']);
			array_push($sub_task_ids, $task['id']);
		}
		// if not index, we expand all tasks
		if ($this->oTask->getFilter()) {
			$this->tns->selected_tasks	= array_merge($this->tns->selected_tasks, $sup_task_ids);
			$this->tns->display_tasks	= array_merge($this->tns->display_tasks, $sub_task_ids);
		}
		// how many tasks in this page ?
		$sum = intval($pager['toNum'] - $pager['frNum']);
		$this->view->sum = ($sum > 1) ? "{$sum} Tasks" : (($sum == 1) ? "One Task" : "Nothing");
		// paging for tasklist
		$this->view->pager = ($pager['totalPage'] > 1) ? $pager : null;
	}
	
    public function plantTaskTree ($finished = false) {
		// get all nodes from task tree
		$tasklist = $this->task_tree->getChilds();
		array_shift($tasklist); // remove root node
		foreach ($tasklist as $key=>$id) {
		    $task = $this->task_tree->getValue($id);
		    $level = $this->task_tree->getLevel($id);
		    $toptask = ($level==1) ? 'toptask' : '';
			// open & close button
			if ($this->task_tree->getChild($id)) {
				if (in_array($task['id'], $this->tns->selected_tasks)) {
					$button = '<a href="javascript:;" onclick="javascript:opentask('.$task['id'].', 0);" /><img src="/images/btn_open.gif"/></a>';
				} else {
					$button = '<a href="javascript:;" onclick="javascript:opentask('.$task['id'].', 1);" /><img src="/images/btn_close.gif"/></a>';
				}
			} else {
				$button = '<img src="/images/btn_leaf.gif"/>';
			}
			// add style for each layer
//			$button = ($level > 1) ? $button : $button;
			// same level, same bgcolor
			$bgcolor = isset($this->bg_color[$level-1]) ? $this->bg_color[$level-1] : '#FFFFFF';
			// highlight selected task
			$selected = ($this->task_id == $task['id']) ? 'style="font-weight:bold;color:#FF3E00;"' : '';
			// create js method
			$onMouseOver = $onMouseOver = ($this->task_id != $task['id']) ? 'onMouseOver="this.style.backgroundColor=\'#F7F9F9\';" onMouseOut="this.style.backgroundColor=\''.$bgcolor.'\';"' : '';
			// create process image
			$procImg = '<img src="'.$this->view->img_url.'?proc='.$task['progress'].'" class="processbar"/>';
			// has attachment
			$attachment = ($task['attachment']) ? '<img src="/images/icon_attach.gif"/>' : '&nbsp;';
			// truncate title 
			$title_full = htmlentities($task['title']);
			$title_shot = Utils::truncate($title_full);
			$title_desc = (strlen($title_full) != strlen($title_shot)) ? 'title="Full Title : ::'.addslashes($title_full).'"' : '';
			// display roadmaps 
			$roadmap_id = (strlen($task['roadmap_id']) > 0) ? $task['roadmap_id'] : '--';
			// display date_end
			$date_end = (isset($task['date_end']) && $task['date_end'] != '0000-00-00') ? $task['date_end'] : 'TBD';
			
			if ($level == 1 || in_array($task['id'], $this->tns->display_tasks)) {
				// For only completed tasks
				if ($finished) {
//					$markable = (isset($task['sup_task_id']) && $task['sup_task_id'] > 0) ? 'disabled' : '';
					$markable = ''; // allow all to grade
					$this->task_content .= 
						'<tr id="task_'.$task['id'].'" class="task '.$toptask.'" style="background:'.$bgcolor.'" '.$onMouseOver.'>
							<td class="folder" style="text-align:left;padding-left:'.intval(($level-1) * 15 + 10).'px;">'.$button.'</td>
							<td class="task_id tasklinkbox"><a href="javascript:viewtask('.$task['id'].')">'.$task['id'].'</a></td>
							<td class="task_attachment">'.$attachment.'</td>
							<td class="task_status">'.$this->oTask->getEntityValue('status', $task['task_status']).'</td>
							<td class="task_prior">'.$this->oTask->getEntityValue('prior', $task['task_prior']).'</td>
							<td class="task_property">'.$this->oTask->getEntityValue('property', $task['property_id']).'</td>
							<td class="task_title title Tips_proc" '.$selected.' '.$title_desc.'>'.$title_shot.'</td>
							<td class="task_requester">'.$this->oTask->getEntityValue('requester', $task['request_id']).'</td>
							<td class="task_manager">'.$this->oTask->getEntityValue('manager', $task['manager_id']).'</td>
							<td class="task_engineer">'.$this->oTask->getEntityValue('engineer', $task['developer_id']).'</td>
							<td class="task_launch_date">'.$task['launch_date'].'</td>
							<td class="task_mark"><input type="button" value="Mark" onclick="javascript:marktask('.$task['id'].')" '.$markable.'/></td>
						</tr>';
				// For Active tasks
				} else {
					$onUpdate = 'onclick="javascript:loadopen(\'/task/edit/id/'.$task['id'].'/p/'.$this->tns->now_page.'\');"';
					$onCreate = 'onclick="javascript:loadopen(\'/task/new/id/'.$task['id'].'/p/'.$this->tns->now_page.'\');"';
					if (!$this->acl->isAllowed(null, 'split')) $onCreate = "disabled"; // Engineer not allow split tasks
					$this->task_content .= 
						'<tr id="task_'.$task['id'].'" class="task '.$toptask.'" >
							<td class="folder" style="text-align:left;padding-left:'.intval(($level-1) * 15 + 10).'px;">'.$button.'</td>
							<td class="task_id tasklinkbox"><a href="javascript:viewtask('.$task['id'].');">'.$task['id'].'</a></td>
							<td class="task_attachment">'.$attachment.'</td>
							<td class="task_status">'.$this->oTask->getEntityValue('status', $task['task_status']).'</td>
							<td class="task_prior">'.$this->oTask->getEntityValue('prior', $task['task_prior']).'</td>
							<td class="task_property">'.$this->oTask->getEntityValue('property', $task['property_id']).'</td>
							<td class="task_title title Tips_proc" '.$selected.' '.$title_desc.'>'.$title_shot.'</td>
							<td class="task_requester">'.$this->oTask->getEntityValue('requester', $task['request_id']).'</td>
							<td class="task_manager">'.$this->oTask->getEntityValue('manager', $task['manager_id']).'</td>
							<td class="task_engineer">'.$this->oTask->getEntityValue('engineer', $task['developer_id']).'</td>
							<td class="task_progress Tips_proc" title="Progress : ::'.$task['progress'].'%">'.$procImg.'</td>
							<td class="task_date_end">'.$date_end.'</td>
							<td class="task_roadmap">'.$roadmap_id.'</td>
							<td class="task_edit"><input type="button" value="Edit" '.$onUpdate.' /></td>
							<td class="task_split"><input type="button" value="Split" '.$onCreate.' /></td>
						</tr>';
				}
			}
		}
		$this->view->task_content = $this->task_content;
    }
    
	public function ajaxCallTaskTree ($finished = false) {
		// ajax request
		if ($this->_getParam('ajax')) {
			$task_function = $this->_getParam('fn');
			$task_selected = $this->_getParam('ti');
			$task_isopened = $this->_getParam('io');
			
			// for task detail
			if ($task_function == 'view') {
				$tasks = $this->oTask->find($task_selected)->toArray();
				if (sizeof($tasks)) {
					$task = $tasks[0];
					$task['property']	= $this->oTask->getEntityValue('property', $task['property_id']);
					$task['requester']	= $this->oTask->getEntityValue('requester', $task['request_id']);
					$task['developer']	= $this->oTask->getEntityValue('engineer', $task['developer_id']);
					$task['manager']	= $this->oTask->getEntityValue('manager', $task['manager_id']);
					$task['prior']		= $this->oTask->getEntityValue('prior', $task['task_prior']);
					$task['type']		= $this->oTask->getEntityValue('status', $task['task_type']);
					$task['status']		= $this->oTask->getEntityValue('status', $task['task_status']);
					$task['process']	= $this->view->img_url.'?proc='.$task['progress'];
					$task['progress']	= $task['progress'].' %';
					$oTaskUpdate = new TaskUpdate();
					$task['task_updates'] = $oTaskUpdate->find('task_id = '.$task['id']);
					$this->view->task	= $task;
				}
				$this->view->upload_url = $this->view->base_url.'upload/id/'.$task['id'];
				return 'detail'; // return view name
			}
			
			// for task marking
			if ($task_function == 'mark') {
				$tasks = $this->oTask->find($task_selected)->toArray();
				if (sizeof($tasks)) {
					$task = $tasks[0];
					$task['property']	= $this->oTask->getEntityValue('property', $task['property_id']);
					$task['requester']	= $this->oTask->getEntityValue('requester', $task['request_id']);
					$task['developer']	= $this->oTask->getEntityValue('engineer', $task['developer_id']);
					$task['manager']	= $this->oTask->getEntityValue('manager', $task['manager_id']);
					$this->view->task	= $task;
				}
				$this->view->upload_url = $this->view->base_url.'upload/id/'.$task['id'];
				$oScore = new Score();
				$tScore = $oScore->fetchRow('task_id = '.$task['id']);
				if ($tScore) {
					$this->view->scorelist = $tScore->toArray();
				}
				return 'mark'; // return view name
			}
			
			// handle task tree 
			if ($task_isopened) {
				$sel_tasks = $this->task_tree->getChild($task_selected);
				array_push($this->tns->selected_tasks, $task_selected);
				$this->tns->display_tasks = array_merge($this->tns->display_tasks, $sel_tasks);
			}
			else {
				$sel_tasks = $this->task_tree->getChilds($task_selected);
				$this->tns->selected_tasks = Utils::array_remove($this->tns->selected_tasks, $sel_tasks);
				array_shift($sel_tasks); // remove self node for closing child tasks
				$this->tns->display_tasks = Utils::array_remove($this->tns->display_tasks, $sel_tasks);
			}
			
//			Utils::dumper($this->tns->selected_tasks);
//			Utils::dumper($this->tns->display_tasks);
			
			return ($finished) ? 'finish-tasklist' : 'tasklist'; // return view name
		}
		// init task tree 
		else {
			$this->tns->selected_tasks	= isset($this->tns->selected_tasks) ? $this->tns->selected_tasks : array();
			$this->tns->display_tasks	= isset($this->tns->display_tasks) ? $this->tns->display_tasks : array();
		}
		return false; // return empty view
	}
	    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // new/edit action support method
    
    public function getTaskWeight () {
    	$tasks_weight = array();
		foreach ($this->_getAllParams() as $key => $param) {
			if (preg_match("/weight_subtask_/i", $key)) {
				$tasks_weight[str_replace("weight_subtask_", "", $key)] = $param;
			}
		}
		return $tasks_weight;
    }
    
    // for subtask weight
    public function pieData ($tasks = array()) {
		$data  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		$data .= "<pie>";
		$loop = 0;
		foreach ($tasks as $task) {
			$pull = ($loop) ? 'false' : 'true'; 
			$data .= "<slice title=\"{$task['title']}\" pull_out=\"{$pull}\">{$task['weight']}</slice>";
			$loop++;
		}
		$data .= "</pie>";
		// for ajax call
		$this->tns->pietask = $tasks;
		$this->tns->piedata = $data;
    }
    
    public function getChildrenWeight ($task_id = 0) {
		$sub_tasks = array();
		if ($task_id <= 0) {
			$this->view->children = $sub_tasks;
		} else {
			$this->initTaskTree();
			$children = $this->task_tree->getChild($task_id);
			if (sizeof($children) > 0) {
				foreach ($children as $child) {
					$task = $this->oTask->find($child)->toArray();
					if (sizeof($task) > 0) {
						array_push($sub_tasks, $task[0]);
					}
				}
			}
			$this->view->children = $sub_tasks;
			// For tasks weight pie chart
			$this->pieData($sub_tasks);
		}
    }
    
    // update suptask schedule
    public function updateTaskSchedule ($tasks = array()) {
    	if (!isset($this->task_tree)) return false;
    	$sub_tasks = $this->task_tree->getChild($this->task_id);
    	// be careful using method 'getParents', possibly to cause dead loop
    	if (sizeof($this->task_tree->getParent($this->task_id)) > 0) {
    		$sup_tasks = $this->task_tree->getParents($this->task_id);
	    	array_shift($sup_tasks); // remove root node
	    	$sup_tasks = array_reverse($sup_tasks);
    	} else {
    		$sup_tasks = array();
    	}
//    	Utils::dumper($sup_tasks);

    	// update this task's schedule
    	if (sizeof($sub_tasks) > 0) {
	    	$progress = 0;
	    	foreach ($sub_tasks as $sub_task) {
	    		$task = $this->oTask->find($sub_task)->toArray();
	    		if (sizeof($task) > 0) {
					$weight	= $task[0]['weight'];
					$proces	= $task[0]['progress'];
					echo $weight." * ".$proces."<br/>";
					$progress += intval(($weight * $proces) / 100);
	    		}
	    	}
	    	$this->oTask->update(array('progress' => $progress), $this->task_id);
    	}
    	
    	// update super task's schedule
    	foreach ($sup_tasks as $sup_task) {
    		$sub_tasks = $this->task_tree->getChild($sup_task);
    		$progress = 0;
    		foreach ($sub_tasks as $sub_task) {
				$task = $this->oTask->find($sub_task)->toArray();
				if (sizeof($task) > 0) {
					$weight	= $task[0]['weight'];
					$proces	= $task[0]['progress'];
//					echo $weight." * ".$proces."<br/>";
					$progress += intval(($weight * $proces) / 100);
				}
    		}
    		$this->oTask->update(array('progress' => $progress), $sup_task);
    	}
    }
   	
   	public function uploadAttachment ($name, $id) {
		$uploadPath = __ROOT_PATH.'/data/tasks/'.$id;
		if (!file_exists($uploadPath)) @mkdir($uploadPath, 0777);
		$extensions = array ("jpg","png","gif","pdf","doc","xls","zip","rar","ppt","eml","mpp","txt","psd");
		$_tempFile  = $_FILES[$name]['tmp_name'];
		$_realName  = $_FILES[$name]['name'];
		$_errormsg  = $_FILES[$name]['error'];
		$_extension = strtolower(str_replace(".", "", strrchr($_realName, ".")));
		if (in_array($_extension, $extensions) && is_uploaded_file($_tempFile) && $_errormsg == 0) {
			$target = $uploadPath.'/'.$_realName;
			if (move_uploaded_file($_tempFile, $target)) {
				@chmod($target, 0777);
				return true;
			}
		}
		return false;
	}
	
	public function getAttachmentIcon ($name) {
		$_extension = strtolower(str_replace(".", "", strrchr($name, ".")));
		switch ($_extension) {
			case 'pdf' :
			case 'doc' :
			case 'xls' :
			case 'rar' :
				return "<img src=\"/images/icon_{$_extension}.gif\" border=\"0\" />";
			default : 
				return "<img src=\"/images/icon_img.gif\" border=\"0\" />";
		}
		return "";
	}
}